#!/bin/bash

# 地理勘查记录系统部署脚本
# 使用方法: ./deploy.sh [dev|prod]

set -e

ENV=${1:-dev}
PROJECT_NAME="geosurvey"

echo "🚀 开始部署 $PROJECT_NAME 项目 (环境: $ENV)"

# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down

# 清理构建缓存（可选）
read -p "是否清理Docker构建缓存？(y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "🧹 清理Docker构建缓存..."
    docker system prune -f
    docker-compose build --no-cache
fi

# 构建镜像
echo "🔨 构建Docker镜像..."
docker-compose build

if [ "$ENV" = "prod" ]; then
    echo "🏭 生产环境部署"
    
    # 检查环境变量
    if [ -z "$DATABASE_URL" ]; then
        echo "⚠️  警告: DATABASE_URL 环境变量未设置，将使用默认配置"
    fi
    
    if [ -z "$SECRET_KEY" ]; then
        echo "❌ 错误: SECRET_KEY 环境变量必须设置"
        exit 1
    fi
    
    # 启动生产环境服务（包括Nginx）
    docker-compose --profile production up -d
    
    echo "🔧 运行数据库迁移..."
    docker-compose exec web python manage.py migrate
    
    echo "👤 创建超级用户..."
    docker-compose exec web python manage.py createsuperuser --noinput || true
    
    echo "📁 收集静态文件..."
    docker-compose exec web python manage.py collectstatic --noinput
    
else
    echo "🔧 开发环境部署"
    
    # 启动开发环境服务
    docker-compose up -d redis postgres
    
    # 等待数据库启动
    echo "⏳ 等待数据库启动..."
    sleep 10
    
    # 启动Web服务
    docker-compose up -d web
    
    echo "🔧 运行数据库迁移..."
    docker-compose exec web python manage.py migrate
    
fi

# 显示服务状态
echo "📊 服务状态:"
docker-compose ps

# 显示日志
echo "📋 显示最近的日志:"
docker-compose logs --tail=50

echo ""
echo "✅ 部署完成!"
echo ""
echo "🌐 访问地址:"
if [ "$ENV" = "prod" ]; then
    echo "   前台: http://localhost (通过Nginx)"
    echo "   API: http://localhost/api/"
    echo "   管理后台: http://localhost/admin/"
else
    echo "   API: http://localhost:8000/api/"
    echo "   管理后台: http://localhost:8000/admin/"
fi
echo "   Redis: localhost:6379"
echo "   PostgreSQL: localhost:5432"
echo ""
echo "📚 常用命令:"
echo "   查看日志: docker-compose logs -f"
echo "   进入容器: docker-compose exec web bash"
echo "   停止服务: docker-compose down"
echo "   重启服务: docker-compose restart"
echo ""
echo "🔧 开发命令:"
echo "   运行测试: docker-compose exec web python manage.py test"
echo "   创建超级用户: docker-compose exec web python manage.py createsuperuser"
echo "   Django Shell: docker-compose exec web python manage.py shell"